package com.example.cachecontroldemo.controller;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.example.cachecontroldemo.pojo.UserDO;
import com.example.cachecontroldemo.pojo.UserVO;
import com.example.cachecontroldemo.service.IUserService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.CacheControl;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.ZoneOffset;
import java.util.Objects;

@RequestMapping("/user")
@RequiredArgsConstructor
@RestController
public class UserController {
    private final IUserService userService;

    @GetMapping("/{userId}")
    public ResponseEntity<UserVO> getUser(@PathVariable String userId) {
        UserDO userDO = userService.getById(userId);
        UserVO userVO = new UserVO(userDO);
        long lastModified = Objects.isNull(userVO.getUpdateTime()) ? 0L : userVO.getUpdateTime().toInstant(ZoneOffset.of("+8")).toEpochMilli();

        return ResponseEntity.ok()
                .lastModified(lastModified)
                .cacheControl(CacheControl.noCache())
                .body(userVO);
    }

    @PutMapping("/rename/{userId}/{name}")
    public ResponseEntity<Boolean> getUser(@PathVariable String userId, @PathVariable String name) {
        boolean update = userService.update(new LambdaUpdateWrapper<UserDO>()
                .set(UserDO::getNickname, name)
                .eq(UserDO::getId, userId));
        return ResponseEntity.ok(update);
    }
}
